/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cratos.xxgram.platf.rongcloud;

import com.cratos.xxgram.platf.base.BaseService;
import com.cratos.xxgram.platf.base.RetCodes;
import com.cratos.xxgram.platf.base.UserInfo;
import com.cratos.xxgram.platf.util.QueueTask;
import static com.cratos.xxgram.platf.rongcloud.NotifyContent.OBJ_CONTRACT_NTF;
import com.cratos.xxgram.platf.rongcloud.RongCloudMessage.RongCloudGroupMessage;
import java.util.List;
import java.net.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.logging.Level;
import javax.annotation.Resource;
import org.redkale.boot.Application;
import org.redkale.convert.json.JsonConvert;
import org.redkale.service.RetResult;
import org.redkale.util.AnyValue;
import org.redkale.util.Comment;
import org.redkale.util.Utility;
import org.redkale.util.ConstructorParameters;

/**
 * 融云SDK接口
 *
 * @author zhangjx
 */
public class RongCloudService extends BaseService {

    @Comment("系统用户ID")
    public static final int SYSTEM_ID = 0;

    @Comment("系统用户ID")
    public static final int ACCPET_SYSTEM_ID = -1;

    @Resource(name = "property.rongcloud.appid")
    protected String ryappid = "vnroth0kvbv9o";

    @Resource(name = "property.rongcloud.secret")
    protected String rysecret = "NMyt1gZgis";

//    @Resource(name = "rongcloud.appid")
//    protected String ryappid = "bmdehs6pbgdzs";
//
//    @Resource(name = "rongcloud.secret")
//    protected String rysecret = "tyJLCn5wOW4";
    @Resource
    protected JsonConvert convert = JsonConvert.root();

    @Comment("透传消息类型")
    private final Map<String, Class> MESSAGE_TYPE = new HashMap<String, Class>();

    @Comment("融云")
    protected final QueueTask<RongCloudMessage> rongCloudMessageQueue = new QueueTask<>(1);

    @Override
    public void init(AnyValue config) {
        super.init(config); //To change body of generated methods, choose Tools | Templates.
        Consumer<RongCloudMessage> rongCloudMessage = (RongCloudMessage message) -> {
           try{
               RetResult<Boolean> result = publishMessage(message);
               if (!result.isSuccess()) {
                    logger.log(Level.SEVERE, "message send fail [" + message.toString() + "] info: "
                            + result.getRetinfo()
                            + "code : " + result.getRetcode() + "response :" + result.getResult());
               }
           }catch(Exception e) {
               e.printStackTrace();
           }
        };
        rongCloudMessageQueue.init(logger, rongCloudMessage);
        initMessageType();// 透传消息类型
    }

    @Comment("透传消息类型初始化")
    private void initMessageType() {
        // 内容消息
        MESSAGE_TYPE.put(BasicContent.OBJ_FILE_MESSAGE, BasicContent.FileMessage.class);
        MESSAGE_TYPE.put(BasicContent.OBJ_TEXT_MESSAGE, BasicContent.TextMessage.class);
        MESSAGE_TYPE.put(BasicContent.OBJ_SIGTH_MESSAGE, BasicContent.SightMessage.class);
        MESSAGE_TYPE.put(BasicContent.OBJ_LBS_MESSAGE, BasicContent.LocationMessage.class);
        MESSAGE_TYPE.put(BasicContent.OBJ_IMAGE_TEXT_MESSAGE, BasicContent.RichContentMessage.class);
        // 通知消息
        MESSAGE_TYPE.put(NotifyContent.OBJ_INFO_NTF, NotifyContent.InformationNotificationMessage.class);
        MESSAGE_TYPE.put(NotifyContent.OBJ_CONTRACT_NTF, NotifyContent.ContactNotificationMessage.class);
        MESSAGE_TYPE.put(NotifyContent.OBJ_PROFILE_NTF, NotifyContent.ProfileNotificationMessage.class);
        MESSAGE_TYPE.put(NotifyContent.OBJ_CMD_NTF, NotifyContent.CommandNotificationMessage.class);
        MESSAGE_TYPE.put(NotifyContent.OBJ_READ_NTF, NotifyContent.ReadReceiptMessage.class);
        //群通知消息
        MESSAGE_TYPE.put(NotifyContent.OBJ_GROUP_NTF, NotifyContent.GroupNotificationMessage.class);
        
        
    }

    @Comment("根据子类型获取消息类型")
    private Class<BaseContent> loadMessageClazzByType(String messageType) {
        if (!MESSAGE_TYPE.containsKey(messageType)) {
            throw new UnsupportedOperationException("unsupport " + messageType + " message ");
        }
        return MESSAGE_TYPE.get(messageType);
    }

    @Comment("透传消息")
    public RetResult pushMessage(String objectName, String messageContent, int fromUserId, int toUserId) {
        Class<BaseContent> messageClazz = loadMessageClazzByType(objectName);
        RongCloudMessage cloudMessage = null;
        if (OBJ_CONTRACT_NTF.equalsIgnoreCase(objectName)) {
            NotifyContent.ContactNotificationMessage notifyContent = convert.convertFrom(NotifyContent.ContactNotificationMessage.class, messageContent);
            notifyContent.setSourceUserId(Integer.toString(fromUserId, 36));
            notifyContent.setTargetUserId(Integer.toString(toUserId, 36));
            cloudMessage = new RongCloudMessage(fromUserId, toUserId, objectName, notifyContent);
        } else {
            BaseContent content = convert.convertFrom(messageClazz, messageContent);
            cloudMessage = new RongCloudMessage(fromUserId, toUserId, objectName, content);
        }
        pubMessage(cloudMessage);
        return RetResult.success();
    }

    public static void main(String[] args) throws Throwable {
        int groupId = 100000004, userId = 300000004;
        String groupName = "testGroup001";
        int joinUserId = 300000014;
        System.out.println(Integer.toString(300000004, 36));
        System.out.println(Integer.toString(300000005, 36));
        RongCloudService service = Application.singleton(RongCloudService.class);
//        service.createGroup(userId, groupId, groupName);
        // 加入群
//        service.joinGroup(joinUserId, groupId,  groupName); 
        int isMentioned = 0;
        int fromUserId = 300000004;
        int toUserId = 0;
        {
                BasicContent.TextMessage content = new BasicContent.TextMessage("我是群里面的文本消息");
                String objectName = BasicContent.TextMessage.TYPE;
                 RongCloudMessage.RongCloudGroupMessage message = new RongCloudMessage
                        .RongCloudGroupMessage(RongCloudMessage.RongCloudGroupMessage.SUB_MSG_DEFAULT,
                                groupId, 
                                isMentioned,
                                fromUserId, 
                                toUserId, 
                                objectName, 
                                content);

                message.setType(RongCloudMessage.GROUP);
//              service.pubMessage(message);
        }    
/***************************************************群通知消息测试*************************************************************************/ 
        {
              NotifyContent.GroupNotificationMessage.CreateGroup createGroupMsg = new NotifyContent.GroupNotificationMessage.CreateGroup();
              createGroupMsg.setOperatorNickname("Rose、666、111等的群聊");
              createGroupMsg.setTargetGroupName("Rose、666、111等的群聊");

              NotifyContent.GroupNotificationMessage co = new NotifyContent.GroupNotificationMessage(Integer.toString(fromUserId, 36), NotifyContent.GroupNotificationMessage.OP_CREATE, createGroupMsg,NotifyContent.GroupNotificationMessage.OP_CREATE_MSG);
              co.setData(createGroupMsg);
              co.setMessage("你好我是通知消息!");
              co.setOperatorUserId(Integer.toString(fromUserId, 36));

              String objectName =  NotifyContent.GroupNotificationMessage.TYPE;
              RongCloudMessage.RongCloudGroupMessage message = new RongCloudMessage
                        .RongCloudGroupMessage(RongCloudMessage.RongCloudGroupMessage.SUB_MSG_DEFAULT,
                                groupId, 
                                isMentioned,
                                fromUserId, 
                                toUserId, 
                                objectName, 
                                co);
                message.setType(RongCloudMessage.GROUP);
                System.out.println(JsonConvert.root().convertTo(message));
                service.pubMessage(message);
        }    
        Thread.sleep(1000 * 10);
    }

    @Comment("创建群组 https://docs.rongcloud.cn/im/server/group/#")
    public CompletableFuture<RetResult> createGroup(int userId, int groupId, String groupName) {
         final CompletableFuture<RetResult> future = new CompletableFuture();
        try {
            String cgroupId = Integer.toString(groupId, 36);
            String cuserId = Integer.toString(userId, 36);
            StringBuilder body = new StringBuilder();
            body.append("userId=").append(URLEncoder.encode(cuserId, UTF_8));
            body.append("&groupId=").append(URLEncoder.encode(cgroupId, UTF_8));
            body.append("&groupName=").append(URLEncoder.encode(groupName, UTF_8));
            String response = http("/group/create.json", body.toString());
            logger.info("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                future.complete(RetResult.success());
                return future;
            }
            future.complete(RetCodes.retResult(RetCodes.RET_GROUP_CREATE_FAILED).result(response));
            return future;
        } catch (Exception e) {
            e.printStackTrace();
            future.complete(RetCodes.retResult(RetCodes.RET_GROUP_CREATE_FAILED));
            return future;
        }
    }

    @Comment("加入群组 https://docs.rongcloud.cn/im/server/group/#")
    public RetResult joinGroup(int userId, int groupId, String groupName) {
        try {
            String cgroupId = Integer.toString(groupId, 36);
            String cuserId = Integer.toString(userId, 36);
            StringBuilder body = new StringBuilder();
            body.append("userId=").append(URLEncoder.encode(cuserId, UTF_8));
            body.append("&groupId=").append(URLEncoder.encode(cgroupId, UTF_8));
            body.append("&groupName=").append(URLEncoder.encode(groupName, UTF_8));
            String response = http("/group/join.json", body.toString());
            System.out.println("joinGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_JOIN_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_JOIN_FAILED);
        }
    }

    @Comment("退出群组 https://docs.rongcloud.cn/im/server/group/#")
    public RetResult quitGroup(int userId, int groupId, String groupName) {
        try {
            String cgroupId = Integer.toString(groupId, 36);
            String cuserId = Integer.toString(userId, 36);
            StringBuilder body = new StringBuilder();
            body.append("userId=").append(URLEncoder.encode(cuserId, UTF_8));
            body.append("&groupId=").append(URLEncoder.encode(cgroupId, UTF_8));
            body.append("&groupName=").append(URLEncoder.encode(groupName, UTF_8));
            String response = http("/group/quit.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_QUIT_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_QUIT_FAILED);
        }
    }

    @Comment("解散群组 https://docs.rongcloud.cn/im/server/group/#")
    public RetResult dismissGroup(int userId, int groupId) {
        try {
            String cgroupId = Integer.toString(groupId, 36);
            String cuserId = Integer.toString(userId, 36);
            StringBuilder body = new StringBuilder();
            body.append("userId=").append(URLEncoder.encode(cuserId, UTF_8));
            body.append("&groupId=").append(URLEncoder.encode(cgroupId, UTF_8));
            String response = http("/group/dismiss.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_DISMISS_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_DISMISS_FAILED);
        }
    }

    @Comment("查询群组成员 https://docs.rongcloud.cn/im/server/group/#")
    public RetResult queryGroup(int groupId) {
        try {
            String cgroupId = Integer.toString(groupId, 36);
            StringBuilder body = new StringBuilder();
            body.append("&groupId=").append(URLEncoder.encode(cgroupId, UTF_8));
            String response = http("/group/user/query.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            QueryGroupResponse resmMessage = JsonConvert.root().convertFrom(QueryGroupResponse.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success(resmMessage.getUsers());
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_QUERY_MEMBER_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_QUERY_MEMBER_FAILED);
        }
    }

    @Comment("刷新群组信息  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult refreshGroup(int groupId, String groupName) {
        try {
            String cgroupId = Integer.toString(groupId, 36);
            StringBuilder body = new StringBuilder();
            body.append("&groupId=").append(URLEncoder.encode(cgroupId, UTF_8));
            body.append("&groupName=").append(URLEncoder.encode(groupName, UTF_8));
            String response = http("/group/refresh.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_QUERY_MEMBER_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_QUERY_MEMBER_FAILED);
        }
    }

    /**
     * userId=2014&group[10001]=TestGroup1&group[10002]=TestGroup2&group[10003]=TestGroup3
     * { group[10001]:TestGroup1, id 统一32 位转换 group[10002]:TestGroup2, id 统一32
     * 位转换 group[10003]:TestGroup3 }
     *
     * @param userId
     * @param groupMap
     * @return
     */
    @Comment("同步用户群组  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult syncGroup(int userId, Map<String, String> groupMap) {
        try {
            String cuserId = Integer.toString(userId, 36);
            StringBuilder body = new StringBuilder();
            body.append("&userId=").append(URLEncoder.encode(cuserId, UTF_8));
            for (String groupKey : groupMap.keySet()) {
                body.append("&").append(groupKey).append("=").append(groupMap.get(groupKey));
            }
            String response = http("/group/sync.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_SYN_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_SYN_FAILED);
        }
    }

    @Comment("群组成员禁言  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult addGroupGag(int userId, int groupId, int minute) {
        try {
            String cuserId = Integer.toString(userId, 36);
            StringBuilder body = new StringBuilder();
            body.append("&userId=").append(URLEncoder.encode(cuserId, UTF_8));
            body.append("&groupId=").append(URLEncoder.encode(Integer.toString(groupId, 36), UTF_8));
            body.append("&minute=").append(minute);
            String response = http("/group/user/gag/add.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_GAGA_ADD_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_GAGA_ADD_FAILED);
        }
    }

    @Comment("取消群组成员禁言  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult rollbackGag(int userId, int groupId) {
        try {
            String cuserId = Integer.toString(userId, 36);
            StringBuilder body = new StringBuilder();
            body.append("&userId=").append(URLEncoder.encode(cuserId, UTF_8));
            body.append("&groupId=").append(URLEncoder.encode(Integer.toString(groupId, 36), UTF_8));
            String response = http("/group/user/gag/rollback.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_ROLLBACK_GAGA_ADD_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_ROLLBACK_GAGA_ADD_FAILED);
        }
    }

    @Comment("获取群组成员禁言列表  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult listGroupGag(int groupId) {
        try {
            StringBuilder body = new StringBuilder();
            body.append("&groupId=").append(URLEncoder.encode(Integer.toString(groupId, 36), UTF_8));
            String response = http("/group/user/gag/list.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_LIST_GAGA_ADD_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_LIST_GAGA_ADD_FAILED);
        }
    }

    @Comment("群组整体禁言列表  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult addBan(int groupId) {
        try {
            StringBuilder body = new StringBuilder();
            body.append("&groupId=").append(URLEncoder.encode(Integer.toString(groupId, 36), UTF_8));
            String response = http("/group/ban/add.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_BAN_ADD_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_BAN_ADD_FAILED);
        }
    }

    @Comment("群组整体禁言列表  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult rollBackBan(int groupId) {
        try {
            StringBuilder body = new StringBuilder();
            body.append("&groupId=").append(URLEncoder.encode(Integer.toString(groupId, 36), UTF_8));
            String response = http("/group/ban/rollback.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_ROLLBACK_BAN_ADD_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_ROLLBACK_BAN_ADD_FAILED);
        }
    }

    @Comment("群组整体禁言列表  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult queryGroupBanadd(int groupId) {
        try {
            StringBuilder body = new StringBuilder();
            body.append("&groupId=").append(URLEncoder.encode(Integer.toString(groupId, 36), UTF_8));
            String response = http("/group/ban/query.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_QUERY_BAN_ADD_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_QUERY_BAN_ADD_FAILED);
        }
    }

    @Comment("禁言用户白名单  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult addWhitelist(int userId, int groupId) {
        try {
            StringBuilder body = new StringBuilder();
            body.append("&groupId=").append(URLEncoder.encode(Integer.toString(groupId, 36), UTF_8));
            body.append("&userId=").append(URLEncoder.encode(Integer.toString(userId, 36), UTF_8));
            String response = http("/group/ban/whitelist/add.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_WHITELIST_ADD_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_WHITELIST_ADD_FAILED);
        }
    }

    @Comment("移除禁言用户白名单  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult rollBackWhitelist(int userId, int groupId) {
        try {
            StringBuilder body = new StringBuilder();
            body.append("&groupId=").append(URLEncoder.encode(Integer.toString(groupId, 36), UTF_8));
            body.append("&userId=").append(URLEncoder.encode(Integer.toString(userId, 36), UTF_8));
            String response = http("/group/ban/whitelist/rollback.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_ROLLBACK_WHITELIST_ADD_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_ROLLBACK_WHITELIST_ADD_FAILED);
        }
    }

    @Comment("移除禁言用户白名单  https://docs.rongcloud.cn/im/server/group/#")
    public RetResult queryWhitelist(int groupId) {
        try {
            StringBuilder body = new StringBuilder();
            body.append("&groupId=").append(URLEncoder.encode(Integer.toString(groupId, 36), UTF_8));
            String response = http("/group/ban/whitelist/query.json", body.toString());
            System.out.println("createGroup response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_GROUP_QUERY_WHITELIST_ADD_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_GROUP_QUERY_WHITELIST_ADD_FAILED);
        }
    }

    @Comment("融云消息发送")
    private final RetResult publishMessage(RongCloudMessage message) {
        int type = message.getType();
        RetResult result = null;
        switch (type) {
            case RongCloudMessage.PRIVATE:
                result = publishPrivateMsg(message);
                break;
            case RongCloudMessage.SYSTEM:
                result = publishSystemMsg(message);
                break;
            case RongCloudMessage.GROUP:
                result = publishGroupMsg(message);
                break;
            case RongCloudMessage.CHATROOM:
                result = publishChatroomMsg(message);
                break;
            default:
                throw new UnsupportedOperationException("unsupport type " + type);
        }
        return result;
    }

    @Comment("单聊消息")
    private RetResult publishPrivateMsg(RongCloudMessage message) {
        try {
            String  url = "/message/private/publish.json";
            String fromUserId = Integer.toString(message.fromUserId, 36);
            String toUserId = Integer.toString(message.toUserId, 36);
            String content = convert.convertTo(message.content);
            String objectName = message.objectName;
            StringBuilder body = new StringBuilder();
            body.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF_8));
            body.append("&toUserId=").append(URLEncoder.encode(toUserId, UTF_8));
            body.append("&objectName=").append(URLEncoder.encode(objectName, UTF_8));
            body.append("&content=").append(URLEncoder.encode(content, UTF_8));
            String response = http(url, body.toString());
            System.out.println("response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_PUBLISHMSG_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_PUBLISHMSG_FAILED);
        }
    }

    @Comment("系统消息")
    private RetResult publishSystemMsg(RongCloudMessage message) {
        try {
            String  url = "/message/system/publish.json";
            String fromUserId = Integer.toString(message.fromUserId, 36);
            String toUserId = Integer.toString(message.toUserId, 36);
            String content = convert.convertTo(message.content);
            String objectName = message.objectName;
            StringBuilder body = new StringBuilder();
            body.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF_8));
            body.append("&toUserId=").append(URLEncoder.encode(toUserId, UTF_8));
            body.append("&objectName=").append(URLEncoder.encode(objectName, UTF_8));
            body.append("&content=").append(URLEncoder.encode(content, UTF_8));
            String response = http(url, body.toString());
            System.out.println("response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_PUBLISHMSG_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_PUBLISHMSG_FAILED);
        }
    }

    @Comment("聊天室消息")
    public RetResult publishChatroomMsg(RongCloudMessage message) {
        return RetResult.success();
    }

    @Comment("群组消息")
    public RetResult publishGroupMsg(RongCloudMessage message) {
        try {
            String url = "/message/group/publish.json";
            String fromUserId = Integer.toString(message.fromUserId, 36);
            String toUserId = Integer.toString(message.toUserId, 36);
            String content = convert.convertTo(message.content);
            String objectName = message.objectName;
            StringBuilder body = new StringBuilder();
            body.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF_8));
            if (!"0".equals(toUserId)) {
                body.append("&toUserId=").append(URLEncoder.encode(toUserId, UTF_8));
            }
            body.append("&objectName=").append(URLEncoder.encode(objectName, UTF_8));
            body.append("&content=").append(URLEncoder.encode(content, UTF_8));
            RongCloudGroupMessage groupMessage = (RongCloudGroupMessage) message;
            /**
             * 状态消息接口
             */
            if (groupMessage.getMsgSubtype() == RongCloudGroupMessage.SUB_MSG_STATUS) {
                url = "/statusmessage/grouppublish/.json";
            }
            body.append("&toGroupId=").append(URLEncoder.encode(groupMessage.getToGroupId(), UTF_8));
            String response = http(url, body.toString());
            logger.info("response=========>>>" + response);
            ResponseMessage resmMessage = JsonConvert.root().convertFrom(ResponseMessage.class, response);
            if (resmMessage.isSuccess()) {
                return RetResult.success();
            }
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_PUBLISHMSG_FAILED).result(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_PUBLISHMSG_FAILED);
        }
    }

    public RetResult<Integer> updateUser(UserInfo user) {
        try {
            StringBuilder body = new StringBuilder();
            body.append("userId=").append(URLEncoder.encode(Integer.toString(user.getUserid(), 36), UTF_8));
            body.append("&name=").append(URLEncoder.encode(user.getUsername(), UTF_8));
            if (user.getFace() != null && !user.getFace().isEmpty()) {
                body.append("&portraitUri=").append(URLEncoder.encode(user.getFace(), UTF_8));
            }
            String content = http("/user/refresh.json", body.toString());
            Map<String, String> map = JsonConvert.root().convertFrom(JsonConvert.TYPE_MAP_STRING_STRING, content);
            if (!"200".equals(map.get("code"))) {
                return RetCodes.retResult(RetCodes.RET_USER_UPDATE_FAILED);
            }
            return RetResult.success(0);
        } catch (Exception e) {
            return RetCodes.retResult(RetCodes.RET_USER_UPDATE_FAILED);
        }
    }

    public RetResult<String> insertUser(UserInfo user) {
        try {
            StringBuilder body = new StringBuilder();
            body.append("userId=").append(URLEncoder.encode(Integer.toString(user.getUserid(), 36), UTF_8));
            body.append("&name=").append(URLEncoder.encode(user.getUsername(), UTF_8));
            if (user.getFace() != null && !user.getFace().isEmpty()) {
                body.append("&portraitUri=").append(URLEncoder.encode(user.getFace(), UTF_8));
            }
            String content = http("/user/getToken.json", body.toString());
            Map<String, String> map = JsonConvert.root().convertFrom(JsonConvert.TYPE_MAP_STRING_STRING, content);
            if (!"200".equals(map.get("code"))) {
                return RetCodes.retResult(RetCodes.RET_USER_SIGNUP_FAILED);
            }
            String token = map.get("token");
            if (token != null && !token.isEmpty()) {
                return new RetResult<>(token);
            }
            return RetCodes.retResult(RetCodes.RET_USER_SIGNUP_FAILED);
        } catch (Exception e) {
            return RetCodes.retResult(RetCodes.RET_USER_SIGNUP_FAILED);
        }
    }

    protected String http(String url, String body) throws Exception {
        String nonce = "1792666679";// String.valueOf(Math.random() * 1000000);
        String timestamp = "1573190691";
        String.valueOf(System.currentTimeMillis());
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update((rysecret + nonce + timestamp).getBytes("utf-8"));
        byte[] digest = md.digest();
        String sign = Utility.binToHexString(digest);
        System.out.println("---------sgin: " + sign);
        System.out.println("---------body: " + body);
        HttpURLConnection conn = (HttpURLConnection) new URL("http://api-cn.ronghub.com" + url).openConnection();
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        conn.setRequestProperty("Host", "minaapi-cn.ronghub.com");
        conn.setRequestProperty("App-Key", ryappid);
        conn.setRequestProperty("Nonce", nonce);
        conn.setRequestProperty("Timestamp", timestamp);
        conn.setRequestProperty("Signature", sign);
        conn.setRequestProperty("User-Agent", "rc-java-sdk/3.0.8");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        if (body != null && !body.isEmpty()) {
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.getOutputStream().write(body.getBytes(UTF_8));
        }
        String content = Utility.read(conn.getInputStream());
        conn.disconnect();
        return content;
    }

    @Comment("发布消息给融云服务器")
    public void pubMessage(RongCloudMessage message) {
        rongCloudMessageQueue.add(message);
    }

    /**
     *
     * @author SquRab
     */
    public static class ResponseMessage {

        String code;
        private static final String SUCCESS = "200";

        @ConstructorParameters(value = {"code"})
        public ResponseMessage(String code) {
            this.code = code;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public boolean isSuccess() {
            return SUCCESS.equalsIgnoreCase(code);
        }

    }

    // {"code":200,"users":[{"id":"4ym1hg"}]}
    public static class QueryGroupResponse {

        public String code;

        private List<User> users;

        @ConstructorParameters(value = {"code", "users"})
        public QueryGroupResponse(String code, List<User> users) {
            this.code = code;
            this.users = users;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public List<User> getUsers() {
            return users;
        }

        public void setUsers(List<User> users) {
            this.users = users;
        }
        public boolean isSuccess() {
            return SUCCESS.equalsIgnoreCase(code);
        }
        private static final String SUCCESS = "200";

        public static class User {

            private String id;

            public String getId() {
                return id;
            }

            public void setId(String id) {
                this.id = id;
            }

        }
    }
}
